<?php
namespace Api\Service;

/**
 * 快递公司
 */
class ExpressService
{
    /**
     * 快递公司列表
     * @return [type] [description]
     */
    public function lists()
    {
        $express = S('express');
        if (!$express || true) {
            $express = M('express')
                ->field('com,name')
                ->select();
            S('express', $express);
        }

        return $express;
    }

    /**
     * 物流信息
     * @param  [type] $com        [description]
     * @param  [type] $express_no [description]
     * @return [type]             [description]
     */
    public function traces($com, $express_no)
    {
        $traces = S('traces_' . $com . '_' . $express_no);
        if (!$traces || true) {

            $conf = $this->defaultApi();
            if (!$conf) {
                return [];
            }

            $key = $conf['key'];

            $res = Vendor('Express.' . $key);

            $Express = new $key(json_decode($conf['conf'], true));

            $traces = $Express->traces($com, $express_no);
            S('traces_' . $com . '_' . $express_no, $traces, 60); // 缓存一分钟
        }

        return $traces ? $traces : [];

    }

    /**
     * 获取默认第三方服务
     * @return [type] [description]
     */
    protected function defaultApi()
    {
        $conf = M('express_setting')
            ->field('key,conf')
            ->where([
                'is_open'    => 1,
                'is_default' => 1,
            ])->find();
        return $conf ? $conf : false;
    }
}
